package com.ruoyi.blog.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.cms.domain.Article;
import com.ruoyi.cms.service.AdultService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.easywenku.entity.StudentDetails;
import com.ruoyi.easywenku.service.StudentDetailsService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@Slf4j
public class ApiStudentDetailsController {
    private static final String prefix = "adultexam";
    @Autowired
    private StudentDetailsService studentDetailsService;

    @Autowired
    private AdultService adultService;

    /**
     * 学生详情
     *
     * @param model
     * @return
     */
    @GetMapping({"/studentDetails"})
    public String school(Model model, @RequestParam(required = false) String phone, @RequestParam(required = false) String verify) {


        List<Article> applicationCheats = (List<Article>) AdultExamController.blogCache.get("applicationCheats");
        if (applicationCheats == null) {
            applicationCheats = adultService.ArticleByCategPage("70", 1, 7);
            applicationCheats.addAll(adultService.ArticleByCategPage("71", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("72", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("73", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("74", 1, 7));
            applicationCheats.addAll(adultService.ArticleByCategPage("75", 1, 7));
            AdultExamController.blogCache.put("applicationCheats", applicationCheats);
        }

        List<Article> latestTestQuestions = (List<Article>) AdultExamController.blogCache.get("latestTestQuestions");
        if (latestTestQuestions == null) {
            latestTestQuestions = adultService.ArticleByCategPage("44", 1, 7);
            latestTestQuestions.addAll(adultService.ArticleByCategPage("49", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("53", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("58", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("62", 1, 7));
            latestTestQuestions.addAll(adultService.ArticleByCategPage("66", 1, 7));
            AdultExamController.blogCache.put("latestTestQuestions", latestTestQuestions);
        }

        model.addAttribute("latestTestQuestions", latestTestQuestions);
        model.addAttribute("applicationCheats", applicationCheats);

        model.addAttribute("blockType", "studentDetails");

        if (StrUtil.isEmpty(phone) || StrUtil.length(verify) < 4) {
            model.addAttribute("islogin", "false");
            return prefix + "/studentDetails";
        }
        StudentDetails one = studentDetailsService.lambdaQuery()
                .eq(StudentDetails::getMobilePhone, phone)
                .likeLeft(StudentDetails::getIdentificationNumber, verify).one();
        if (one != null) {
            model.addAttribute("studentDetails", one);
        } else {
            model.addAttribute("islogin", "true");
        }

        return prefix + "/studentDetails";
    }

    /**
     * 保存学生详情
     *
     * @param studentDetails s
     * @return
     */
    @PostMapping({"/saveStudentDetails"})
    @ResponseBody
    @SneakyThrows
    public R saveStudentDetails(StudentDetails studentDetails/*
            ,@RequestParam("frontPhotoOfIdCardf") MultipartFile frontPhotoOfIdCard
            ,@RequestParam("backPhotoOfIdCardf") MultipartFile backPhotoOfIdCard
            ,@RequestParam("photoOfGraduationCertificatef") MultipartFile photoOfGraduationCertificate
            ,@RequestParam("medicalCertificatePhotosf") MultipartFile medicalCertificatePhotos
            ,@RequestParam("blueBackgroundPhotof") MultipartFile blueBackgroundPhoto*/
    ) {
        // 上传文件路径
   /*     String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        if(!frontPhotoOfIdCard.isEmpty()){
            studentDetails.setFrontPhotoOfIdCard(FileUploadUtils.upload(filePath, frontPhotoOfIdCard));
        }
        if(!backPhotoOfIdCard.isEmpty()){
            studentDetails.setFrontPhotoOfIdCard(FileUploadUtils.upload(filePath, backPhotoOfIdCard));
        }
        if(!photoOfGraduationCertificate.isEmpty()){
            studentDetails.setFrontPhotoOfIdCard(FileUploadUtils.upload(filePath, photoOfGraduationCertificate));
        }
        if(!medicalCertificatePhotos.isEmpty()){
            studentDetails.setFrontPhotoOfIdCard(FileUploadUtils.upload(filePath, medicalCertificatePhotos));
        }
        if(!blueBackgroundPhoto.isEmpty()){
            studentDetails.setFrontPhotoOfIdCard(FileUploadUtils.upload(filePath, blueBackgroundPhoto));
        }*/
        if (StrUtil.isBlank(studentDetails.getMobilePhone())) {
            return R.failed("手机号不能为空");
        }
        StudentDetails one = studentDetailsService.lambdaQuery().eq(StudentDetails::getIdentificationNumber, studentDetails.getIdentificationNumber()).one();
        if(one!=null){
            return R.failed("","身份证号码重复");
        }else {
            studentDetails.setSubmissionTime(DateUtil.now());
            studentDetails.setChangeTime(DateUtil.now());
            studentDetailsService.save(studentDetails);
        }

        return R.ok();
    }


    /*

        {
  "form": "NP5eRC",
  "form_name": "成人教育招生报名",
  "entry": {
    "serial_number": 123,
    "field_23": "张三",
    "field_24": "选项1",
    "field_4": "这是一行文字",
    "field_33": "这是一行文字",
    "field_34": "这是一行文字",
    "field_29": "13812345678",
    "field_36": "这是一行文字",
    "field_42": "这是一行文字",
    "field_30": "这是一行文字",
    "field_35": "这是一行文字",
    "field_37": "这是一行文字",
    "field_38": "这是一行文字",
    "field_39": "这是一行文字",
    "field_31": {
      "province": "陕西省",
      "city": "西安市",
      "district": "雁塔区",
      "street": "高新路"
    },
    "field_43": "这是一行文字",
    "field_44": [
      {
        "statement": "2013年",
        "dimensions": {
          "收入": "10万",
          "支出": "2万"
        }
      },
      {
        "statement": "2014年",
        "dimensions": {
          "收入": "20万",
          "支出": "10万"
        }
      }
    ],
    "field_45": [
      "https://example.jinshuju.net/en/key1?token=token&download"
    ],
    "field_46": [
      "https://example.jinshuju.net/en/key1?token=token&download"
    ],
    "field_47": [
      "https://example.jinshuju.net/en/key1?token=token&download"
    ],
    "field_48": [
      "https://example.jinshuju.net/en/key1?token=token&download"
    ],
    "field_49": [
      "https://example.jinshuju.net/en/key1?token=token&download"
    ],
    "field_50": "这是一行文字",
    "creator_name": "小王",
    "created_at": "2021-08-19T08:44:54.911Z",
    "updated_at": "2021-08-19T08:44:54.911Z",
    "info_remote_ip": "127.0.0.1"
  }
}
        * */

    /**
     * 金数据数据导入
     */
    @PostMapping({"/goldDataDataImport"})
    @ResponseBody
    @SneakyThrows
    public String goldDataDataImport(HttpServletRequest request) {
        String form = IoUtil.read(request.getInputStream(), "utf-8");
        log.info(form);
        JSONObject json = JSONObject.parseObject(form);
        if (!"NP5eRC".equals(json.get("form"))) {
            return "ok";
        }
        JSONObject entry = json.getJSONObject("entry");
        StudentDetails studentDetails = new StudentDetails();

        studentDetails.setName(entry.getString("field_23"));
        studentDetails.setGender(entry.getString("field_24"));
        studentDetails.setNationality(entry.getString("field_4"));
        studentDetails.setIdentificationNumber(entry.getString("field_33"));
        studentDetails.setPoliticalStatus(entry.getString("field_34"));
        studentDetails.setMobilePhone(entry.getString("field_29"));
        studentDetails.setBackupPhone(entry.getString("field_36"));
        studentDetails.setMail(entry.getString("field_42"));
        /*studentDetails.setWechat(entry.getString("field_30"));*/
        studentDetails.setGraduatedSchool(entry.getString("field_35"));
        studentDetails.setGraduationCertificateNumber(entry.getString("field_37"));
        studentDetails.setGraduationDate(entry.getString("field_38"));
        studentDetails.setPlaceOfResidence(entry.getString("field_39"));
        JSONObject field31 = entry.getJSONObject("field_31");
     /*   studentDetails.setExaminationProvince(field31.getString("province"));
        studentDetails.setExaminationCity(field31.getString("city"));
        studentDetails.setExaminationCounty(field31.getString("district"));*/
        studentDetails.setReviewMaterialsAddress(entry.getString("field_43"));
        JSONArray field44 = entry.getJSONArray("field_44");


        studentDetails.setCollegeName1(field44.getJSONObject(0).getJSONObject("dimensions").getString("院校名称（代码）"));
        studentDetails.setApplicationMajor1(field44.getJSONObject(0).getJSONObject("dimensions").getString("报考专业（代码）"));
        studentDetails.setLevel1(field44.getJSONObject(0).getJSONObject("dimensions").getString("层次"));
        studentDetails.setSubjectName1(field44.getJSONObject(0).getJSONObject("dimensions").getString("科类名称"));
        studentDetails.setModality1(field44.getJSONObject(0).getJSONObject("dimensions").getString("形式（函授/业余）"));

        studentDetails.setCollegeName2(field44.getJSONObject(1).getJSONObject("dimensions").getString("院校名称（代码）"));
        studentDetails.setApplicationMajor2(field44.getJSONObject(1).getJSONObject("dimensions").getString("报考专业（代码）"));
     /*   studentDetails.setLevel2(field44.getJSONObject(1).getJSONObject("dimensions").getString("层次"));
        studentDetails.setSubjectName2(field44.getJSONObject(1).getJSONObject("dimensions").getString("科类名称"));
        studentDetails.setModality2(field44.getJSONObject(1).getJSONObject("dimensions").getString("形式（函授/业余）"));
*/
        studentDetails.setCollegeName3(field44.getJSONObject(2).getJSONObject("dimensions").getString("院校名称（代码）"));
        studentDetails.setApplicationMajor3(field44.getJSONObject(2).getJSONObject("dimensions").getString("报考专业（代码）"));
/*        studentDetails.setLevel3(field44.getJSONObject(2).getJSONObject("dimensions").getString("层次"));
        studentDetails.setSubjectName3(field44.getJSONObject(2).getJSONObject("dimensions").getString("科类名称"));
        studentDetails.setModality3(field44.getJSONObject(2).getJSONObject("dimensions").getString("形式（函授/业余）"));

        studentDetails.setFrontPhotoOfIdCard(entry.getString("field_45"));
        studentDetails.setBackPhotoOfIdCard(entry.getString("field_46"));
        studentDetails.setPhotoOfGraduationCertificate(entry.getString("field_47"));
        studentDetails.setMedicalCertificatePhotos(entry.getString("field_48"));
        studentDetails.setBlueBackgroundPhoto(entry.getString("field_49"));
        studentDetails.setAdmissionsTeacher(entry.getString("field_50"));*/
        studentDetailsService.save(studentDetails);


        return "ok";
    }

}
